package org.example.forum.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.example.forum.config.AppConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 登录拦截器
 */
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Value("${forum.login.url}")
    private String defaultURL;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession(false);
        if(null != session&&session.getAttribute(AppConfig.USER_SESSION) != null) {
            //用户登录状态，校验通过
            return true;
        }
        //校验url是否正确
        if(!defaultURL.startsWith("/")) {
            defaultURL = "/"+defaultURL;
        }
        //校验不通过跳转登陆页面
        response.sendRedirect(defaultURL);
        return false;
    }
}
